package com.atguigu.datastream.test.day05;

import com.atguigu.datastream.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;

/**
 * ClassName: Flink02_CountWindow
 * Package: com.atguigu.test.day05
 * Description:
 *           countwindow计算窗口
 * @Author ChenJun
 * @Create 2023/4/11 22:52
 * @Version 1.0
 */
public class Flink02_CountWindow {
    public static void main(String[] args) throws Exception {

        //1. 创建流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2. 从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3. 将书转换为javabean对象

        SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");

                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });


        //3.将相同的key聚合到一起
        KeyedStream<WaterSensor, String> keyedStream = map.keyBy(new KeySelector<WaterSensor, String>() {
            @Override
            public String getKey(WaterSensor value) throws Exception {
                return value.getId();
            }
        });

        // TODO 开启一个窗口大小为5 的计数滚动窗口
        WindowedStream<WaterSensor, String, GlobalWindow> countWindow = keyedStream.countWindow(5);

        // 聚合vc
        SingleOutputStreamOperator<WaterSensor> vc = countWindow.sum("vc");
        vc.print();

        env.execute();

    }
}
